package org.realteam.hibernate.test.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.realteam.hibernate.test.model.inheritance.Cat;
import org.realteam.hibernate.test.model.inheritance.Employee;
import org.realteam.hibernate.test.model.inheritance.JessCat;
import org.realteam.hibernate.test.model.inheritance.Person;
import org.realteam.hibernate.test.model.inheritance.Student;
import org.realteam.hibernate.test.model.inheritance.Teacher;
import org.realteam.hibernate.test.model.inheritance.TomCat;

public class HibernateUtil {
	
	private static Log log = LogFactory.getLog(HibernateUtil.class);
	
	private static final SessionFactory sessionFactory = buildSessionFactory();

//	private static SessionFactory buildSessionFactory() {
//		
//		try {
//			return new Configuration()
//				.addAnnotatedClass(Cat.class)
//				.addAnnotatedClass(TomCat.class)
//				.addAnnotatedClass(JessCat.class)
//				.configure()
//				.buildSessionFactory();
//		} catch (Throwable e) {
//			log.debug("create and initial hibernate sessionFacotry faild.");
//			log.debug(e.getMessage());
//			throw new ExceptionInInitializerError(e);
//		}
//	}
	
	@SuppressWarnings("deprecation")
	private static SessionFactory buildSessionFactory() {
		
		try	{
			return new Configuration()
				.configure()
				.addPackage("org.realteam.hibernate.test.model.inheritance")
				.addAnnotatedClass(Cat.class)
				.addAnnotatedClass(TomCat.class)
				.addAnnotatedClass(JessCat.class)
				.addAnnotatedClass(Person.class)
				.addAnnotatedClass(Student.class)
				.addAnnotatedClass(Teacher.class)
				.addAnnotatedClass(Employee.class)
				.buildSessionFactory();
		} catch (Throwable e) {
			log.debug("create and initial hibernate sessionFactory faild.");
			log.debug(e.getMessage());
			throw new ExceptionInInitializerError(e);
		}
	}
	
	public static void exportDDLScript(Configuration config, String fileName) {
		SchemaExport export = new SchemaExport(config);
		export.setOutputFile(fileName);
		export.create(true, true);
	}
	
	public static SessionFactory getSessionFacotry() {
		return sessionFactory;
	}
	
	public static void main(String[] args) {
		buildSessionFactory();
	}
	
}
